package com.skyline.attraction.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.skyline.attraction.dao.AttractionDao;
import com.skyline.attraction.dao.AttractionFeatureDao;
import com.skyline.attraction.dao.RatyDao;
import com.skyline.attraction.model.Ratyable;
import com.skyline.attraction.service.RatyService;
import com.skyline.attraction.type.RatyType;
import com.skyline.base.exception.NoResourceException;
import com.skyline.base.type.Activity;

@Service("ratyService")
public class RatyServiceImpl implements RatyService {
	@Autowired
	private RatyDao ratyDao;
	@Autowired
	private AttractionDao attractionDao;
	@Autowired
	private AttractionFeatureDao attractionFeatureDao;

	@Override
	public boolean hasRaty(Long id, RatyType type, Long userId) {
		Integer count = ratyDao.countUserRaty(id, type, userId);
		return (count != null && count > 1);
	}

	@Override
	public Ratyable ratyStar(Long id, RatyType type, Long userId, Integer ratyStar) {
		Ratyable target = null;
		switch (type) {
		case ATTRACTION:
			target = attractionDao.queryAttractionById(id, Activity.NORMAL);
			break;
		case FEATURE:
			target = attractionFeatureDao.queryFeatureById(id, Activity.NORMAL);
			break;
		default:
			return null;
		}

		if (target == null) {
			throw new NoResourceException("评分时资源不存在");
		}

		int votes = target.getVotes();
		float oldStar = target.getStar();
		int newVotes = votes + 1;
		float newStar = (oldStar * votes + ratyStar) / (newVotes);

		switch (type) {
		case ATTRACTION:
			attractionDao.updateAttractionStar(id, newStar);
			break;
		case FEATURE:
			attractionFeatureDao.updateStar(id, newStar);
			break;
		default:
			return null;
		}

		ratyDao.insertRaty(id, type, userId, ratyStar);

		target.setStar(newStar);
		target.setVotes(newVotes);

		return target;
	}

}
